package com.driving.exam.spider;

import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import com.driving.exam.entity.Exercise;
import com.driving.exam.service.IDrivingExamService;
import com.driving.exam.spider.parser.DrivingExamParser;

import cn.guet.base.spider.BaseTask;
import cn.guet.base.spider.Constants;
import cn.guet.base.spider.DirectoryUtil;

/**
 * 下载题库任务
 *
 * @author SAGITTAR
 */
@Component(value = "drivingExamSpider")
public class DrivingExamSpider extends BaseTask<IDrivingExamService, Exercise, DrivingExamParser> {

    private static final Logger LOGGER = LogManager.getLogger(DrivingExamSpider.class);

    private static final String BASE_DIRECTORY = "E:/drivinglm/exercise/";

    private static final List<String> FILE_LIST;

    static {
        FILE_LIST = new ArrayList<>();
        FILE_LIST.add("kemu1/A1-A3-B1.txt");
        FILE_LIST.add("kemu1/A2-B2.txt");
        FILE_LIST.add("kemu1/C1-C2.txt");
        FILE_LIST.add("kemu4/A1-A2-A3-B1-B2.txt");
        FILE_LIST.add("kemu4/C1-C2.txt");
    }

    public void execute() throws Exception {
        for (String file : FILE_LIST) {
            String fileDirectory = DirectoryUtil.getCorrectDirectory(BASE_DIRECTORY, file);
            RandomAccessFile randomAccessFile = new RandomAccessFile(fileDirectory, "r");
            String line;
            List<Exercise> exerciseList = new ArrayList<>();
            while (StringUtils.isNotBlank((line = randomAccessFile.readLine()))) {
                line = new String(line.getBytes("ISO-8859-1"), Constants.UTF_8);
                if (StringUtils.isNotBlank(line)) {
                    LOGGER.warn(line);
                    // 0为编号；1为章节；2为题目；3-6为选项（如果有），7为答案，8为图片（如果有），9未知，10为解析，11-12未知
                    String[] info = line.split(",");
                    Exercise exercise = new Exercise();
                    exercise.setSubjectId(Integer.parseInt(StringUtils.substringBetween(file, "kemu", "/")));
                    exercise.setType(StringUtils.substringBetween(file, "/", "."));
                    exercise.setChapter(Integer.parseInt(trimQuotation(info[1])));
                    exercise.setTitle(trimQuotation(info[2]));
                    List<String> choiceList = new ArrayList<>();
                    choiceList.add(trimQuotation(info[3]));
                    choiceList.add(trimQuotation(info[4]));
                    if (StringUtils.isNotBlank(trimQuotation(info[5]))) {
                        choiceList.add(trimQuotation(info[5]));
                    }
                    if (StringUtils.isNotBlank(trimQuotation(info[6]))) {
                        choiceList.add(trimQuotation(info[6]));
                    }
                    exercise.setChoiceList(choiceList);
                    exercise.setAnswer(Integer.parseInt(trimQuotation(info[7])));
                    if (StringUtils.isNotBlank(trimQuotation(info[8]))) {
                        exercise.setPicture(trimQuotation(info[8]));
                    }
                    exercise.setExplanation(trimQuotation(info[10]));
                    exercise.setOrdinal(Integer.parseInt(trimQuotation(info[0]).trim()));
                    exerciseList.add(exercise);
                }
            }
            randomAccessFile.close();
            int everyTime = 30;
            int times = 0;
            while (times * everyTime < exerciseList.size()) {
                int start = times++ * everyTime;
                if (start > exerciseList.size()) {
                    break;
                }
                int end = start + everyTime;
                if (end > exerciseList.size()) {
                    end = exerciseList.size();
                }
                baseService.insertBatch(parser.parse(exerciseList.subList(start, end)), end - start);
                Thread.sleep(1000 * 3);
            }
            Thread.sleep(1000 * 5);
        }
    }

    /**
     * 去除两端引号
     *
     * @return
     */
    private String trimQuotation(String info) {
        return StringUtils.remove(info, "\"");
    }
}
